<?php

namespace App\Traits;

use Symfony\Component\HttpFoundation\Response;

trait ApiResponse
{
    /**
     * @var int
     */
    protected $statusCode = Response::HTTP_OK;

    /**
     * @return mixed
     */
    public function getStatusCode ()
    {
        return $this->statusCode;
    }

    /**
     * @param $statusCode
     * @param null $httpCode
     * @return $this
     */
    public function setStatusCode ($statusCode, $httpCode = null)
    {
        $httpCode = $httpCode ?? $statusCode;
        $this->statusCode = $httpCode;
        return $this;
    }

    /**
     * @param $data
     * @param array $header
     * @return mixed
     */
    public function respond ($data, $header = [])
    {
        return response()->json($data, $this->getStatusCode(), $header);
    }

    /**
     * @param $status
     * @param array $data
     * @param null $code
     * @return mixed
     */
    public function status ($status, array $data, $code = null)
    {
        if ($code){
            $this->setStatusCode($code);
        }
        $status = [
            'status' => $status,
            'code'   => $this->statusCode
        ];

        $data = array_merge($status,$data);
        return $this->respond($data);
    }

    /**
     * @param $message
     * @param int $code
     * @param string $status
     * @return mixed
     */
    public function failed ($message = '操作失败，参数错误！', $code = Response::HTTP_BAD_REQUEST, $status = 'error')
    {
        return $this->setStatusCode($code)->message($message,$status);
    }

    /**
     * @param $data
     * @param string $status
     * @param string $message
     * @return mixed
     */
    public function success ($data = [], $message = '请求成功！', $status = "success")
    {
        return $this->status($status, compact('message', 'data'));
    }

    /**
     * @param $message
     * @param string $status
     * @return mixed
     */
    public function message ($message, $status = "success")
    {
        return $this->status($status, [
            'message' => $message
        ]);
    }

    /**
     * @param string $message
     * @return mixed
     */
    public function internalError ($message = "Internal Error!")
    {
        return $this->failed($message, Response::HTTP_INTERNAL_SERVER_ERROR);
    }
}
